package com.usefullc.extinguisher.component;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.usefullc.common.constants.SubPubConstants;
import com.usefullc.common.context.ContextManager;
import com.usefullc.common.util.JsonUtil;
import com.usefullc.extinguisher.constant.ExtinguisherConstant;
import com.usefullc.extinguisher.domain.FireDevice;
import com.usefullc.extinguisher.domain.FireDeviceAuditRecord;
import com.usefullc.extinguisher.enums.DeviceAuditRecordStatusEnum;
import com.usefullc.extinguisher.query.FireDeviceAuditRecordQuery;
import com.usefullc.extinguisher.query.FireDeviceQuery;
import com.usefullc.extinguisher.service.FireDeviceAuditRecordService;
import com.usefullc.extinguisher.service.FireDeviceService;
import com.usefullc.system.domain.JobTemplate;
import com.usefullc.system.enums.JobTemplatePeriodEnum;
import com.usefullc.system.service.JobTemplateService;
import com.usefullc.system.service.component.SystemConfigComponent;
import com.usefullc.system.service.component.redis.SubPubMessage;
import com.usefullc.system.service.component.redis.SubPubMessageConsume;
import com.usefullc.system.service.component.scheduler.IQuartzHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author: Sampson
 * @date: 2022-02-01 20:05
 */
@Slf4j
@Service
public class DeviceAuditConsume implements SubPubMessageConsume {

    @Autowired
    private SystemConfigComponent systemConfigComponent;

    @Autowired
    private JobTemplateService jobTemplateService;

    @Autowired
    private FireDeviceService fireDeviceService;

    @Autowired
    private FireDeviceAuditRecordService fireDeviceAuditRecordService;

    @Autowired
    private IQuartzHelper quartzHelper;


    @Override
    public void consume(SubPubMessage subPubMessage) {
        if(!systemConfigComponent.getAppName().equals(subPubMessage.getAppName())){
            return;
        }

        String messageKey = SubPubConstants.JOB+"_"+ ExtinguisherConstant.JOB_CATEGORY_FIRE+"_";
        if(StringUtils.startsWith(subPubMessage.getKey(),messageKey)){
            Object data = subPubMessage.getData();
            FireDeviceQuery fireDeviceQuery = JsonUtil.json2Bean(data.toString(), FireDeviceQuery.class);
//            HashMap<String, Object> dataMap = (HashMap<String, Object>) fireDeviceQuery1

            Long jobTemplateId = Long.valueOf(StringUtils.removeStart(subPubMessage.getKey(),messageKey));
            try{
                log.info("device consume start,jobTemplateId={},参数={}",jobTemplateId,data);

                Long batchNo = System.currentTimeMillis();
                DateTime date = DateUtil.date();
                JobTemplate jobTemplate = jobTemplateService.findById(jobTemplateId);
                Integer period = jobTemplate.getPeriod();
                JobTemplatePeriodEnum jobTemplatePeriodEnum = JobTemplatePeriodEnum.getByCode(period);
                switch (jobTemplatePeriodEnum){
                    case DAY:batchNo = DateUtil.beginOfDay(date).getTime();break;
                    case WEEK:batchNo = DateUtil.beginOfWeek(date).getTime();break;
                    case MONTH:batchNo = DateUtil.beginOfMonth(date).getTime();break;
                    case QUARTER:batchNo = DateUtil.beginOfQuarter(date).getTime();break;
                    case YEAR:batchNo = DateUtil.beginOfYear(date).getTime();break;
                }
                //构建任务
                //获取deviceId
//                FireDeviceQuery fireDeviceQuery = new FireDeviceQuery();
//                fireDeviceQuery.setType(dataMap.get("type"));
                List<FireDevice> dataList = fireDeviceService.findAll(fireDeviceQuery);

                if (CollectionUtils.isNotEmpty(dataList)) {
                    log.info("build fireDevice audit size={}",dataList.size());
                    for (FireDevice fireDevice : dataList) {
                        //如果有历史任务未审核的，标记为漏打卡,暂不做 todo
//                        FireDeviceAuditRecordQuery fireDeviceAuditRecordQuery = new FireDeviceAuditRecordQuery();
//                        fireDeviceAuditRecordQuery.setStatus(DeviceAuditRecordStatusEnum.NOT_AUDIT.getCode());
//                        fireDeviceAuditRecordQuery.setDeviceId(fireDevice.getId());
//                        fireDeviceAuditRecordQuery.setJobId(jobTemplateId);
//                        List<FireDeviceAuditRecord> fireDeviceAuditRecords = fireDeviceAuditRecordService.findAll(fireDeviceAuditRecordQuery);
//                        if (CollectionUtils.isNotEmpty(fireDeviceAuditRecords)) {
//                            for (FireDeviceAuditRecord fireDeviceAuditRecord : fireDeviceAuditRecords) {
//                                fireDeviceAuditRecord.setStatus(DeviceAuditRecordStatusEnum.MISS_AUDIT.getCode());
//                                fireDeviceAuditRecordService.update(fireDeviceAuditRecord);
//                            }
//                        }

                        //如果当前周期内已经有了，就不用再生产了


                        try{
                            FireDeviceAuditRecord fireDeviceAuditRecord = new FireDeviceAuditRecord();
                            fireDeviceAuditRecord.setDeviceId(fireDevice.getId());
                            fireDeviceAuditRecord.setJobId(jobTemplateId);
                            fireDeviceAuditRecord.setStatus(DeviceAuditRecordStatusEnum.NOT_AUDIT.getCode());
                            fireDeviceAuditRecord.setBatchNo(batchNo);
                            fireDeviceAuditRecordService.save(fireDeviceAuditRecord);


                            //如果是异常，则不清空，2023.07月需求
                            if(fireDevice.getStatus() != DeviceAuditRecordStatusEnum.ERROR.getCode()){
                                fireDevice.setStatus(DeviceAuditRecordStatusEnum.NOT_AUDIT.getCode());
                                fireDeviceService.update(fireDevice);
                            }

                        }catch (Exception e){
                            log.warn("build fire device audit record failed,error={}",e);
                        }

                    }
                }
            }catch (Exception e){
                log.error("consume job category failed",e);
            }finally {
                quartzHelper.complete(jobTemplateId.toString());
            }


        }

    }
}
